﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using eztvReaderLib;

namespace eztvReader
{
    /// <summary>
    /// Interaction logic for Loading.xaml
    /// </summary>
    public partial class Loading : Page
    {
        public Loading()
        {
            InitializeComponent();
            bgw.DoWork += bgw_DoWork;
            bgw.WorkerReportsProgress = true;
            bgw.ProgressChanged += bgw_ProgressChanged;
            bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;
        }

        void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if(e.Cancelled == false)
                this.NavigationService.Navigate(new Contents());
            prgsBar.IsIndeterminate = false;
            txtError.Visibility = System.Windows.Visibility.Visible;
            btnAgain.Visibility = System.Windows.Visibility.Visible;        
        }

        void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if(e.ProgressPercentage == 0)
                Contents.list = (List<ezReader.Item>)e.UserState;
            if (e.ProgressPercentage == 1)
                txtError.Text = "Error loading data: " + e.UserState.ToString();
        }

        void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                bgw.ReportProgress(0, new ezReader().GetXML());
            }
            catch(Exception ex)
            {
                bgw.ReportProgress(1, ex.Message);
                e.Cancel = true;
            }
        }
        private readonly BackgroundWorker bgw = new BackgroundWorker();

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (bgw.IsBusy) return;
            prgsBar.IsIndeterminate = true;
            txtError.Visibility = System.Windows.Visibility.Hidden;
            btnAgain.Visibility = System.Windows.Visibility.Hidden;   
            bgw.RunWorkerAsync();
        }
    }
}
